package com.spirng.leetcode.day01;

import java.util.HashMap;
import java.util.Map;

public class Array5_1 {
    public static void main(String[] args) {
        int i = totalFruit1(new int[]{3, 3, 3, 1,1,2, 1, 1, 2});
        System.out.println(i);
    }
    public static int totalFruit(int[] fruits) {
       int slow=0,fast=0,result=0;
       int n=fruits.length;
       int sub=0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for(;fast<n;fast++){
            map.put(fruits[fast],map.getOrDefault(fruits[fast],0)+1);
            while (map.size()>2){
                map.put(fruits[slow],map.getOrDefault(fruits[slow],0)-1);
                if(map.get(fruits[slow])==0){
                    map.remove(fruits[slow]);
                }
                slow++;
            }
            sub = Math.max(sub, fast - slow + 1);
        }
        return sub;
    }
    public static int totalFruit1(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
        int left = 0, ans = 0;
        for (int right = 0; right < n; ++right) {
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            while (cnt.size() > 2) {
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

}
